﻿module Sustainalytics.ScrollPager {

    import Common = Sustainalytics.Common;

    interface IScrollPagerScope extends ng.IScope {
        skip: number;
        take: number;
        lastScrollTop: number;
        forWindow: boolean;
        resetScroll: boolean;
        locked: boolean;
    }

    function scrollPagerDirective($timeout: ng.ITimeoutService) {
        return {
            restrict: 'EA',

            scope: {
                skip: '=pagerScrollSkip',
                take: '=pagerScrollTake',
                forWindow: '@pagerScrollForwindow',
                resetScroll: '=pagerScrollReset',
                locked: '=pagerScrollLocked'
            },

            link: function (scope: IScrollPagerScope, element, attrs) {

                scope.lastScrollTop = 0;

                evalReset();

                var el;
                var scrollHeightFunc;
                var outerHeightFunc;

                if (!scope.forWindow) {
                    el = angular.element(element);
                    scrollHeightFunc = () => element.scrollHeight;
                    outerHeightFunc = () => el.outerHeight()
                }
                else {
                    el = angular.element(document);
                    scrollHeightFunc = () => $(document).height();
                    outerHeightFunc = () => $(window).outerHeight();
                }

                el.on('scroll', function () {

                    if (scope.locked) {
                        return;
                    }

                    var scrollTop = el.scrollTop();

                    if (scrollHeightFunc() == (scrollTop + outerHeightFunc())) {

                        evalReset();

                        // set new skip + take
                        if (scrollTop > scope.lastScrollTop) {                            
                            scope.lastScrollTop = scrollTop;
                            scope.skip = scope.skip + scope.take;
                        }
                    }
                });

                function evalReset() {
                    if (scope.resetScroll) {
                        scope.skip = 0;
                        scope.lastScrollTop = 0;
                        scope.resetScroll = false;
                    }
                }
            }
        };
    };

    export var scrollPagerDirectiveName = 'sustainalyticsPagerScroll';

    angular.module(scrollPagerModuleName).directive(scrollPagerDirectiveName, scrollPagerDirective);
}